package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.tool.ToolClient;
import com.fwtai.web.UserIntegralBuyDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 用户使用积分购买商品记录（积分可当货款）业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-04-24 11:40:33
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class UserIntegralBuyService{

  private final UserIntegralBuyDao userIntegralBuyDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public UserIntegralBuyService(final UserIntegralBuyDao userIntegralBuyDao,final ThreadPoolTaskExecutor taskExecutor){
    this.userIntegralBuyDao = userIntegralBuyDao;
    this.taskExecutor = taskExecutor;
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,Object> map = userIntegralBuyDao.queryById(kid);
      final List<HashMap<String,Object>> list = userIntegralBuyDao.getBuyDetails(kid);
      final HashMap<String,Object> result = new HashMap<>(2);
      result.put("goodsOrder",map);
      if(list != null){
        result.put("orderDetails",list);
      }
      return ToolClient.queryJson(result);
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> userIntegralBuyDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> userIntegralBuyDao.getListTotal(formData),taskExecutor);
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}